package com.zzyl.intercept;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 执行方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前方法是否是请求Controller的方法，HandlerMethod指处理特定请求的方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
//        获取token并判断是否为空，如果为空就返回401
        String token = request.getHeader(Constants.USER_TOKEN);
        if(ObjectUtil.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        解析token，如果结果为空就返回401
        Claims claims = JwtUtil.parseJWT(secretKey, token);
        if(ObjectUtil.isEmpty(claims)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        获取token携带的用户数据，如果为空就返回401
        Object obj = claims.get("currentUser");
        if(ObjectUtil.isEmpty(obj)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        解析数据，获取用户信息对象
        String userJson = JSONUtil.toJsonStr(obj);
        UserVo vo = JSONUtil.toBean(userJson, UserVo.class);

//        从缓存里获取当前用户可访问的所有资源，如果资源为空就返回401
        String json = redisTemplate.opsForValue().get(SuperConstant.USER_RESOURCE + vo.getId());
        if(ObjectUtil.isEmpty(json)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        解析数据，获取资源集合，组装当前请求路径
        List<String> pathUrls = JSONUtil.toList(json, String.class);
        String path = request.getMethod()+request.getRequestURI();
        for (int i = 0; i < pathUrls.size(); i++) {
//            判断当前请求是否在资源集合里，在就把用户数据存入ThreadLocal
            if(antPathMatcher.match(pathUrls.get(i),path)){
                UserThreadLocal.setSubject(userJson);
                UserThreadLocal.set(vo.getId());
                return true;
            }
        }
//        如果请求不在资源集合里就返回403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }

    /**
     * 执行方法之后执行。清除ThreadLocal里的数据
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
